using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using log4net;

namespace SQLRunner.uiStatus
{
    /// <summary>
    /// Set of controls that change a property value to TRUE or FALSE
    /// depending of a state value
    /// </summary>
    public class PropertyStateList
    {

        #region Private Instances

        private readonly string _property;
        private readonly State _flag;
        private readonly List<Component> _controls;
        private static readonly ILog _log = LogManager.GetLogger(typeof(PropertyStateList).FullName);

        #endregion
        #region Public Methods

        public PropertyStateList(string property, State flag)
        {
            _property = property;
            _flag = flag;
            _controls = new List<Component>();
        }

        public void AddControl(Component control)
        {
            Type t = control.GetType();
            IEnumerator iterator = t.GetProperties().GetEnumerator();
            bool isFound = false;
			
            while ( !isFound & iterator.MoveNext())
            {
                PropertyInfo property = (PropertyInfo) iterator.Current;
                if ( property.Name.Equals(_property) )
                {
                    _controls.Add(control);
                    isFound = true;
                }
            }
            if (!isFound && _log.IsWarnEnabled)
            {
                _log.Warn(
                    String.Format("Property {0} was not found in control {1}", _property, control));
            }
        }

        public void UpdateProperty(State state)
        {
            bool value = (_flag & state) == state? true : false; 
            foreach (Component control in _controls)
            {
                Type t = control.GetType();
                PropertyInfo property = t.GetProperty(_property);
                property.SetValue(control, value, null);
            }
        }

        public override string ToString()
        {
            StringBuilder strB = new StringBuilder();
            strB.AppendLine(String.Format("PropertyStateList"));
            strB.AppendLine(String.Format("\tProperty: {0}", _property));
            strB.AppendLine(String.Format("\tState: {0}", _flag));
            strB.AppendLine("\tControls:");
            foreach (Component control in _controls)
            {
                strB.AppendLine(String.Format("\t\t{0}", control));
            }
            return strB.ToString();
        }

        #endregion


    }
}